<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
    <el-form-item label="用户昵称" prop="nickname">
      <el-input v-model="form.nickname" placeholder="请输入用户昵称" maxlength="30" />
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUserProfile } from '@/api/user'
import { validPhone, validEmail } from '@/utils/validate'

const emit = defineEmits(['success'])

const props = defineProps({
  user: {
    type: Object,
    required: true
  }
})

// 表单对象
const form = reactive({
  nickname: '',
  phone: '',
  email: ''
})

// 表单校验规则
const rules = {
  nickname: [
    { required: true, message: '用户昵称不能为空', trigger: 'blur' },
    { min: 2, max: 30, message: '用户昵称长度必须介于 2 和 30 之间', trigger: 'blur' }
  ],
  phone: [
    { validator: (rule, value, callback) => {
      if (value && !validPhone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  email: [
    { validator: (rule, value, callback) => {
      if (value && !validEmail(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ]
}

const formRef = ref(null)

// 监听用户数据变化
watch(() => props.user, (val) => {
  if (val) {
    form.nickname = val.nickname
    form.phone = val.phone
    form.email = val.email
  }
}, { immediate: true, deep: true })

// 提交表单
const submit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateUserProfile(form)
        ElMessage.success('个人信息修改成功')
        emit('success')
      } catch (error) {
        console.error('修改个人信息失败:', error)
        ElMessage.error('修改个人信息失败')
      }
    }
  })
}
</script> 